﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO.Compression;
using System.IO;

namespace AudioCore.Common
{
    public class HttpWebResponseDecompressed : System.Net.WebResponse
    {
        private HttpWebResponse response;
        public HttpWebResponseDecompressed(WebRequest request)
        {
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }

            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
        }

        public override void Close()
        {
            response.Close();
        }

        public override Stream GetResponseStream()
        {
            if (response.ContentEncoding == "gzip")
            {
                return new GZipStream(response.GetResponseStream(),
                    CompressionMode.Decompress);
            }

            else if (response.ContentEncoding == "deflate")
            {
                return new DeflateStream(response.GetResponseStream(),
                    CompressionMode.Decompress);
            }

            else
            {
                if (response.StatusCode == HttpStatusCode.InternalServerError)
                    return new GZipStream(response.GetResponseStream(),
                        CompressionMode.Decompress);

                return response.GetResponseStream();
            }
        }

        public override long ContentLength
        {
            get { return response.ContentLength; }
        }

        public override string ContentType
        {
            get { return response.ContentType; }
        }

        public override System.Net.WebHeaderCollection Headers
        {
            get { return response.Headers; }
        }

        public override System.Uri ResponseUri
        {
            get { return response.ResponseUri; }
        }

    } 
}
